package com.nx.platform.es.biz.query.count;


import com.nx.platform.es.biz.query.count.cache.CountCaches;
import com.nx.platform.es.biz.query.count.handler.CountRequestHandlerChain;
import com.nx.platform.es.common.utils.CommonUtils;
import org.elasticsearch.action.search.SearchResponse;

/**
 * @author
 * @since 2016年10月21日
 */
public class CountRequestProcessor {

    private final CountRequestHandlerChain handlerChain;
    private final CountCaches countCaches;

    public CountRequestProcessor(CountRequestHandlerChain handlerChain, CountCaches countCaches) {
        this.handlerChain = handlerChain;
        this.countCaches = countCaches;
    }

    public long request(CountRequestContext context) throws Exception {
        // 请求预处理
        handlerChain.handle(context);
        String trace = context.getTrace().toString();
        String cacheKey = CommonUtils.toMD5(trace);
        context.setCacheKey(cacheKey);
        boolean useCache = context.getExpireAfterWrite() > 0 && !context.isNocache();

        // 尝试取缓存
        if (useCache) {
            Long cached = countCaches.getCache().get(context.getLogPrefix(), cacheKey);
            if (cached != null) {
                return cached;
            }
        }

        // 取缓存失败时执行ES请求
        SearchResponse response = context.getEsClient().getClient().search(context.getRequest());
        context.setResponse(response);
        Long result = response == null ? 0L : response.getHits().getTotalHits();

        // 请求结果写入缓存
        if (useCache) {
            countCaches.getCache().put(context.getLogPrefix(), cacheKey, result, context.getExpireAfterWrite());
        }
        return result;
    }

}